﻿#include"BinaryDispatch.hpp"
#include"Session.hpp"
#include"../Concurrency/Lock.hpp"

namespace MMFNetwork{

    BinaryDispatch::BinaryDispatch(const BinMsgCallback& defaultCallback)
        : mDefaultCallback(defaultCallback)
    {

    }
        
    BinaryDispatch::~BinaryDispatch()
    {

    }
    
    void BinaryDispatch::HandleMessage(const std::shared_ptr<Session>& session, void* pkg, size_t size)
    {
        //从内存池申请内存
        MMFMessageHeader* msg = (MMFMessageHeader*)mMemPool.Alloc((uint32_t)size);
        memcpy(msg, pkg, size);
        const char* msgName = msg->mName;

        //加锁
        mLock.Lock();

        //获取回调函数
        std::unordered_map<const std::string_view, BinMsgCallback>::iterator it = mMsgCallback.find(msgName);
        BinMsgCallback* handler = &mDefaultCallback;
        if (it != mMsgCallback.end())
           handler = &(it->second);

        //解锁
        mLock.Unlock();

        //调用回调
        (*handler)(session, msg);

        //释放内存
        mMemPool.Free(msg);
    }

    bool BinaryDispatch::RegisterCallback(const char* msgName, BinMsgCallback callback)
    {
        //加锁
        MMF::LockGuard lk(mLock);

        std::unordered_map<const std::string_view, BinMsgCallback>::iterator it = mMsgCallback.find(msgName);
        if (it != mMsgCallback.end())
            return false;

        mMsgCallback.emplace(msgName, callback);

        return true;
    }

    bool BinaryDispatch::UnregisterCallback(const char* msgName)
    {
        //加锁
        MMF::LockGuard lk(mLock);

        std::unordered_map<const std::string_view, BinMsgCallback>::iterator it = mMsgCallback.find(msgName);
        if (it == mMsgCallback.end())
            return false;

        mMsgCallback.erase(it);

        return true;
    }
}